#include "echo.h"

// ================================================================================

#define BUF_LEN 1024

int main(int argc, char *argv[]) {
  int svr_sock;
  int reuseaddr_val;
  sockaddr_in_t svr_host;
  char buf[BUF_LEN];

  svr_sock = socket(AF_INET, SOCK_DGRAM, 0);
  if (svr_sock == -1) {
    perror("Failed to create a network socket");
    return 1;
  }

  reuseaddr_val = 1;
  setsockopt(svr_sock, SOL_SOCKET, SO_REUSEADDR, &reuseaddr_val, sizeof(int));

  svr_host.sin_family = AF_INET;
  svr_host.sin_port = htons(ECHO_PORT);
  svr_host.sin_addr.s_addr = INADDR_ANY;

  if (bind(svr_sock, (sockaddr_t*)&svr_host, sizeof(svr_host)) == -1) {
    perror("Failed to bind to the network socket");
    close(svr_sock);
    return 1;
  }

  for (;;) {
    sockaddr_in_t addr;
    socklen_t addrlen = sizeof(addr);

    int len = recvfrom(svr_sock, buf, BUF_LEN, 0, (sockaddr_t*)&addr, &addrlen);
    if (len > 0) {
      buf[len] = 0;
      printf("Received from %s:%d: %s\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), buf);
      sendto(svr_sock, buf, len, 0, (sockaddr_t*)&addr, addrlen);
    } else {
      perror("Failed to receive a UDP datagram from a remote host");
    }
  }

  close(svr_sock);

  return 0;
}
